package cn.kai.basic.controller;

import cn.kai.basic.util.AjaxResult;
import cn.kai.basic.util.FastdfsUtil;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;

@RestController
@RequestMapping("/fastDfs")
public class FastdfsController {
    //文件上传接口
    @PostMapping
    public AjaxResult upload(@RequestPart(value = "file") MultipartFile file){
        try {
            String fileName = file.getOriginalFilename(); //获取真实路径（得到上传时的文件名）
            System.out.println(fileName);
            String extension = FilenameUtils.getExtension(fileName); //获取文件的后缀名
            System.out.println(extension);
            String path = FastdfsUtil.upload(file.getBytes(), extension);
            return AjaxResult.me().setResultObj(path);
        }catch (IOException e){
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMsg("系统繁忙，请重试");
        }
    }
    //文件删除接口
    @DeleteMapping
    public AjaxResult delete(@RequestParam(value = "path",required = true) String path){
        try {
            String pathTmp = path.substring(1);
            String groupName = pathTmp.substring(0, pathTmp.indexOf("/"));
            String remotePath = pathTmp.substring(pathTmp.indexOf("/") + 1);
            FastdfsUtil.delete(groupName,remotePath);
            return AjaxResult.me();
        }catch (Exception e){
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMsg("系统繁忙，请重试");
        }
    }
}
